<template>
  <div>
    <AppHeader />
    <div class="address-container">
      <div class="address-header">
        <h2>
          <el-icon><MapLocation /></el-icon> 收货地址管理
        </h2>
        <div class="header-actions">
          <span class="address-count">共 {{ addressList.length }} 个地址</span>
          <el-button type="primary" @click="openAddDialog" :icon="Plus" class="add-btn" round>
            添加新地址
          </el-button>
        </div>
      </div>

      <div class="address-list">
        <el-skeleton :rows="5" animated :loading="loading && addressList.length === 0" />

        <div v-for="address in addressList" :key="address.shippingId" class="address-card"
             :class="{ 'default-address': address.isDefault === 1 }">
          <div class="card-header">
            <div class="user-info">
              <span class="receiver">{{ address.receiverName }}</span>
              <span class="region-badge">{{ address.receiverProvince }}</span>
              <el-tag v-if="address.isDefault === 1" type="success" size="small" effect="light" round>
                <el-icon><StarFilled /></el-icon> 默认
              </el-tag>
            </div>
            <div class="card-actions">
              <el-button link type="primary" @click="openEditDialog(address)" :icon="Edit" circle :loading="loading" />
              <el-button link type="danger" @click="handleDelete(address.shippingId)" :icon="Delete" circle :loading="loading" />
            </div>
          </div>

          <div class="address-detail">
            <div class="detail-item">
              <el-icon><User /></el-icon>
              <span>{{ address.receiverName }}</span>
            </div>
            <div class="detail-item">
              <el-icon><Iphone /></el-icon>
              <span>{{ formatPhone(address.receiverPhone) }}</span>
            </div>
            <div class="detail-item">
              <el-icon><LocationInformation /></el-icon>
              <span>{{ address.receiverProvince }} {{ address.receiverCity }} {{ address.receiverDistrict }}</span>
            </div>
            <div class="detail-item">
              <el-icon><OfficeBuilding /></el-icon>
              <span>{{ address.receiverAddress }}</span>
            </div>
            <div class="detail-item" v-if="address.receiverZip">
              <el-icon><Postcard /></el-icon>
              <span>邮编: {{ address.receiverZip }}</span>
            </div>
          </div>

          <div class="card-footer">
            <el-button v-if="address.isDefault !== 1" type="primary" link @click="setAsDefault(address.shippingId)" :loading="loading">
              <el-icon><Star /></el-icon>设为默认地址
            </el-button>
            <el-button v-else disabled type="success" link>
              <el-icon><StarFilled /></el-icon>当前默认地址
            </el-button>
          </div>
        </div>

        <div v-if="!loading && addressList.length === 0" class="empty-address">
          <el-empty description="暂无收货地址" :image-size="200">
            <el-button type="primary" @click="openAddDialog">添加第一个地址</el-button>
          </el-empty>
        </div>
      </div>
    </div>

    <!-- 地址编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="currentAddress.shippingId ? '编辑地址' : '添加新地址'" width="600px">
      <el-form ref="addressForm" :model="currentAddress" :rules="rules" label-width="100px">
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="currentAddress.receiverName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="receiverPhone">
          <el-input v-model="currentAddress.receiverPhone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="所在地区" required>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="receiverProvince">
                <el-select v-model="currentAddress.receiverProvince" placeholder="省" filterable @change="handleProvinceChange">
                  <el-option v-for="province in provinces" :key="province" :label="province" :value="province" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="receiverCity">
                <el-select v-model="currentAddress.receiverCity" placeholder="市" filterable :disabled="!cities.length" @change="handleCityChange">
                  <el-option v-for="city in cities" :key="city" :label="city" :value="city" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="receiverDistrict">
                <el-select v-model="currentAddress.receiverDistrict" placeholder="区/县" filterable :disabled="!districts.length">
                  <el-option v-for="district in districts" :key="district" :label="district" :value="district" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="receiverAddress">
          <el-input
              v-model="currentAddress.receiverAddress"
              type="textarea"
              placeholder="街道、小区、楼栋号等"
              :rows="3"
          />
        </el-form-item>
        <el-form-item label="邮政编码">
          <el-input v-model="currentAddress.receiverZip" placeholder="请输入邮政编码" />
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch v-model="currentAddress.isDefault" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">保存地址</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { useStore } from 'vuex'
import request from '../../utils/request'
import regionData from '../../assets/china-region.json'
import {
  Location, Plus, Star, StarFilled, User, Iphone,
  LocationInformation, OfficeBuilding, Edit, Delete,
  MapLocation, Place, Postcard
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AppHeader from '../Header.vue'

const store = useStore()

// 从store获取用户信息
const currentUser = computed(() => store.state.currentUser)
const userId = computed(() => currentUser.value?.userId || null)

const addressList = ref([])
const dialogVisible = ref(false)
const loading = ref(false)
const addressForm = ref(null)

const currentAddress = ref({
  shippingId: null,
  userId: null,
  receiverName: '',
  receiverPhone: '',
  receiverProvince: '',
  receiverCity: '',
  receiverDistrict: '',
  receiverAddress: '',
  receiverZip: '',
  isDefault: 0
})

const rules = {
  receiverName: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  receiverPhone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  receiverProvince: [{ required: true, message: '请选择省份', trigger: 'blur' }],
  receiverCity: [{ required: true, message: '请选择城市', trigger: 'blur' }],
  receiverDistrict: [{ required: true, message: '请选择区县', trigger: 'blur' }],
  receiverAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

const formatPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

const fetchAddresses = async () => {
  if (!userId.value) {
    ElMessage.error('用户信息无效，请重新登录')
    return
  }
  
  loading.value = true
  try {
    const response = await request.get('/user/address', {
      params: { userId: userId.value }
    })
    addressList.value = response.data.addresses || []
  } catch (error) {
    ElMessage.error('获取地址列表失败: ' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

const initForm = () => {
  currentAddress.value = {
    shippingId: null,
    userId: userId.value,
    receiverName: '',
    receiverPhone: '',
    receiverProvince: '',
    receiverCity: '',
    receiverDistrict: '',
    receiverAddress: '',
    receiverZip: '',
    isDefault: 0
  }
}

// 省市区联动数据
const provinces = ref(regionData.map(item => item.province))
const cities = ref([])
const districts = ref([])

// 监听省份变化，更新城市
const handleProvinceChange = (provinceName) => {
  const provinceData = regionData.find(item => item.province === provinceName)
  if (provinceData && provinceData.citys) {
    cities.value = provinceData.citys.map(item => item.city)
  } else {
    cities.value = []
  }
  districts.value = []
  currentAddress.value.receiverCity = ''
  currentAddress.value.receiverDistrict = ''
}

// 监听城市变化，更新区县
const handleCityChange = (cityName) => {
  const provinceData = regionData.find(item => item.province === currentAddress.value.receiverProvince)
  if (provinceData) {
    const cityData = provinceData.citys.find(item => item.city === cityName)
    if (cityData && cityData.areas) {
      districts.value = cityData.areas.map(item => item.area)
    } else {
      districts.value = []
    }
  } else {
    districts.value = []
  }
  currentAddress.value.receiverDistrict = ''
}

// 编辑时初始化联动
const initRegionSelect = () => {
  if (currentAddress.value.receiverProvince) {
    handleProvinceChange(currentAddress.value.receiverProvince)
    if (currentAddress.value.receiverCity) {
      handleCityChange(currentAddress.value.receiverCity)
    }
  }
}

const openAddDialog = () => {
  if (!userId.value) {
    ElMessage.error('用户信息无效，请重新登录')
    return
  }
  initForm()
  dialogVisible.value = true
  nextTick(() => {
    initRegionSelect()
  })
}

const openEditDialog = (address) => {
  if (!userId.value) {
    ElMessage.error('用户信息无效，请重新登录')
    return
  }
  currentAddress.value = JSON.parse(JSON.stringify(address))
  dialogVisible.value = true
  nextTick(() => {
    initRegionSelect()
  })
}

const submitForm = async () => {
  if (!userId.value) {
    ElMessage.error('用户信息无效，请重新登录')
    return
  }
  
  try {
    await addressForm.value.validate()
    loading.value = true

    const addressData = {
      ...currentAddress.value,
      userId: userId.value
    }

    if (addressData.shippingId) {
      // 更新地址
      const { data } = await request.put('/user/address', addressData)
      if (data.status === 200) {
        ElMessage.success('地址更新成功')
        dialogVisible.value = false
        fetchAddresses()
      } else {
        ElMessage.error(data.msg || '更新失败')
      }
    } else {
      // 新增地址
      const { data } = await request.post('/user/address', addressData)
      if (data.status === 200) {
        ElMessage.success('地址添加成功')
        dialogVisible.value = false
        fetchAddresses()
      } else {
        ElMessage.error(data.msg || '添加失败')
      }
    }
  } catch (error) {
    if (error.name !== 'ValidateError') {
      ElMessage.error('操作失败: ' + (error.response?.data?.msg || error.message))
    }
  } finally {
    loading.value = false
  }
}

const handleDelete = async (shippingId) => {
  if (!userId.value) {
    ElMessage.error('用户信息无效，请重新登录')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除该地址吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    })

    loading.value = true
    const { data } = await request.delete(`/user/address/${shippingId}`, {
      params: { userId: userId.value }
    })

    if (data.status === 200) {
      ElMessage.success('删除成功')
      fetchAddresses()
    } else {
      ElMessage.error(data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message))
    }
  } finally {
    loading.value = false
  }
}

const setAsDefault = async (shippingId) => {
  if (!userId.value) {
    ElMessage.error('用户信息无效，请重新登录')
    return
  }
  
  try {
    loading.value = true
    const { data } = await request.put(`/user/address/${shippingId}/default`, null, {
      params: { userId: userId.value }
    })

    if (data.status === 200) {
      ElMessage.success('设置默认地址成功')
      fetchAddresses()
    } else {
      ElMessage.error(data.msg || '设置失败')
    }
  } catch (error) {
    ElMessage.error('设置默认地址失败: ' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (userId.value) {
    fetchAddresses()
  }
})
</script>

<style scoped>
.address-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.address-header {
  margin-bottom: 30px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.address-header h2 {
  margin: 0 0 15px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-count {
  font-size: 14px;
}

.add-btn {
  border-radius: 20px;
  padding: 8px 20px;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
}

.address-card {
  border: 1px solid #e6e8eb;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.address-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.default-address {
  border: 1px solid var(--el-color-primary);
  background-color: rgba(64, 158, 255, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px dashed #eee;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.receiver {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.region-badge {
  font-size: 12px;
  padding: 2px 8px;
  background-color: #f0f2f5;
  border-radius: 10px;
  color: #666;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.address-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 14px;
  color: #555;
}

.detail-item .el-icon {
  color: #999;
  margin-top: 2px;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px dashed #eee;
}

.empty-address {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #eee;
  margin-right: 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid #eee;
}

/* 表单输入框样式优化 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  margin-bottom: 8px;
  display: block;
}
</style>